package com.snow.common.config;

import feign.RequestInterceptor;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.Objects;

/**
 * All rights Reserved, Designed By www.cusc.com
 *
 * @author yanke
 * @Title: FeignConfig
 * @Package com.snow.common.config
 * @Description:类描述
 * @Email yanke@cu-sc.com
 * @version: v1.0.0
 * @date: 2021/4/27/0027 16:09
 * @Copyright: 2021  www.faw.com.cn Inc. All rights reserved. <br/>
 * Modification History:<br/>
 * Date         Author          Version            Description<br/>
 * *---------------------------------------------------------*<br/>
 * 2021/4/27/0027     Administrator           v1.0.0               修改原因<br/>
 * @since JDK 1.8
 */
@Configuration
public class FeignConfig {

    private final static String REQUESTID = "requestId";

    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            Enumeration<String> headerNames = servletRequestAttributes.getRequest().getHeaderNames();
            if (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                String headerValue = servletRequestAttributes.getRequest().getHeader(headerName);
                requestTemplate.header(headerName, headerValue);
            }
            String requestid = MDC.get(REQUESTID);
            if (Objects.nonNull(requestid)) {
                requestTemplate.header(REQUESTID, requestid);
            }
        };
    }
}
